﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace iLangl.Model
{
	public class ContactResponseContext : BaseResponseContext
	{
		Contact contact = null;
		Contact[] contacts = null;

		public override void SetContext(object context)
		{
			base.SetContext(context);

			if (document == null)
				return;

			XmlNode nodecontact = null;

			if (document.Name != "Contact")
			{
				XmlNode nodecontacts = document.SelectSingleNode("//Contacts");

				if (nodecontacts != null)
				{
					List<Contact> result = new List<Contact>();
					ContactResponseContext responsecontactContext = new ContactResponseContext();

					foreach (XmlNode contactnode in nodecontacts)
					{
						responsecontactContext.SetContext(contactnode);
						result.Add((Contact)responsecontactContext.GetContext());
					}

					contacts = result.ToArray();
					return;
				}
			}
			else if (document.Name == "Contact")
			{
				nodecontact = document;
			}

			if(nodecontact == null)
				nodecontact = document.SelectSingleNode("//Contact");

			if (nodecontact == null)
				return;

			contact = new Contact();
			ParseExtendedInfo(nodecontact, contact);

			if (nodecontact.Attributes["id"] != null)
				contact.Id = nodecontact.Attributes["id"].Value;
			if (nodecontact.Attributes["title"] != null)
				contact.Title = nodecontact.Attributes["title"].Value;

			if (nodecontact.Attributes["firstname"] != null)
				contact.FirstName = nodecontact.Attributes["firstname"].Value;
			if (nodecontact.Attributes["lastname"] != null)
				contact.LastName = nodecontact.Attributes["lastname"].Value;
			if (nodecontact.Attributes["email"] != null)
				contact.Email = nodecontact.Attributes["email"].Value;
			if (nodecontact.Attributes["phone"] != null)
				contact.Phone = nodecontact.Attributes["phone"].Value;

			if (nodecontact.Attributes["companyId"] != null)
			{
				contact.Company = Facade.Instance.ModelFactory.CreateCompany();
				contact.Company.Id = nodecontact.Attributes["companyId"].Value;
			}
		}

		public override object GetContext()
		{
			if (contact != null)
				return contact;

			if (contacts != null)
				return contacts;

			return null;
		}
	}
}
